package com.gouzheng.controller;

import com.gouzheng.entity.User;
import com.gouzheng.service.UserService;
import com.gouzheng.service.impl.UserServiceImpl;
import com.gouzheng.util.BaseBean;
import com.gouzheng.util.CaptchaUtil;
import com.gouzheng.util.MD5;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserControlller {

    @Autowired
    private UserService userService;
    private CaptchaUtil captchaUtil;

    //登录
    @RequestMapping("/login")
    public void login(String username, String password,String code, HttpServletResponse response, HttpServletRequest request, HttpSession session) throws Exception{
        //加密后的
        String pwd= MD5.md5(password);

        User user=userService.login(username,pwd);

        String randCode=(String) session.getAttribute("randCode");
        System.out.println("randCode==="+randCode);
        code=code.toUpperCase();

        if(user == null || code==null || code.isEmpty() || !code.equals(randCode)){
            //把错误信息存入session
            session.setAttribute("msg","登录失败！请检查账号密码验证码是否正确！");
            response.sendRedirect("/index.jsp");

        }else{
            //将user存入session
            session.setAttribute("user",user);
            if(user.getType()==0){
                //超级管理员
                //重定向
                response.sendRedirect(request.getContextPath()+"/user/home");
                //清空session(msg)
                session.removeAttribute("msg");
            }else{
                //学生
                response.sendRedirect(request.getContextPath()+"/user/studentHome");
            }
        }

    }


    @RequestMapping("/studentHome")
    public String studentHome(){
        return "studentHome";
    }

    @RequestMapping("/code")
    @ResponseBody
    public void code(HttpServletResponse response,HttpServletRequest request) throws Exception{
        captchaUtil.outputCaptcha(request,response);
    }



    //跳转至home页面
    @RequestMapping("/home")
    public String home(){
        return "home";
    }
    //跳转至student页面
    @RequestMapping("/student")
    public String student(){
        return "studentDao";
    }

    //查看账号信息
    @RequestMapping("/getAll")
    public String getAll(String names,Integer type, Model model){
        List<User> userList = userService.getAll(names,type);
        model.addAttribute("list",userList);
        return "user";
    }

    @RequestMapping("/addUsers")
    @ResponseBody
    public BaseBean addUsers(User user) throws Exception{
        BaseBean baseBean=new BaseBean();
        String pwd=MD5.md5(user.getPassword());
        //放在对象中
        user.setPassword(pwd);
        Integer row = userService.getAllName(user.getUsername());
        if(row==0){
        userService.addUsers(user);
        baseBean.setMsg("添加成功");
        return baseBean;
      }else{
         baseBean.setMsg("账号已存在");
         return baseBean;
        }
    }

    //注册账号
    @RequestMapping("/addUser")
    @ResponseBody
    public BaseBean addUser(User user) throws Exception{
        BaseBean baseBean=new BaseBean();
        String pwd=MD5.md5(user.getPassword());
        //放在对象中
        user.setPassword(pwd);

        if(user.getType()==1){
            String stuNum=user.getStuNum();
            //验证是否有该学籍
            Integer stuNum1 = userService.getStuNum(stuNum);
            if(stuNum1<1){
               baseBean.setMsg("学籍不存在，请稍后重试");
               return baseBean;
            }
            //判断该学籍是否已有账号
            String stuNum2 = userService.findStuNum(stuNum);
            if(stuNum2 != null){
            baseBean.setMsg("该账号已存在"+stuNum2);
            return baseBean;
        }

        }
        //账号已存在
        Integer row = userService.getAllName(user.getUsername());
        if(row==0){
            userService.addUser(user);
            baseBean.setMsg("注册成功");
            return baseBean;
        }else{
            baseBean.setMsg("账号已存在");
            return baseBean;
        }
    }
    //修改账户信息
    @RequestMapping("/toUpdate")
    public String toupdate(Model model,Integer id) throws Exception{
        User userId = userService.getUserId(id);
        model.addAttribute("lists",userId);
        return "updateUser";
    }
    @RequestMapping("/update")
    public String update(User user){
        userService.updateUser(user);
        return "redirect:/user/getAll";
    }

    //删除账号
    @RequestMapping("/deleteUser/{id}")
    public void deleteUser(@PathVariable("id") Integer id,HttpServletRequest request,HttpServletResponse response) throws Exception{
        userService.deleteUser(id);
        response.sendRedirect(request.getContextPath()+("/user/getAll"));
    }

    //切换账号
    @RequestMapping("/loginOut")
    public String loginOut(HttpSession session){

        //清空Session
        session.removeAttribute("user");
        //写入session
        session.setAttribute("msg","正在切换账户，请输入新的账户！！");
        //跳转至登录页面
        return "redirect:/index.jsp";
    }

    //跳转至userInfo页面
    @RequestMapping("/userInfo")
    public String userInfo(){
        return "userInfo";
    }

    //导出
    @RequestMapping("/downloadExcel")
    public void setUpExcel(HttpServletResponse response,String names,Integer type) {
        String[] headers = {"姓名","账号","密码","账户类型"};
        //查询所有用户
        List<User> userList=userService.getAll(names,type);
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        //设置列宽
        sheet.setDefaultColumnWidth((short) 18);
        //创建第一行的对象，第一行一般用于填充标题内容。从第二行开始一般是数据0:1
        HSSFRow row = sheet.createRow(0);
        for (short i = 0; i < headers.length; i++) {
            //创建单元格，每行多少数据就创建多少个单元格
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            //给单元格设置内容
            cell.setCellValue(text);
        }
        //遍历集合，将每个集合元素对象的每个值填充到单元格中
        for(int i=0;i<userList.size();i++){
            //获取到某一个对象
            User tbUser=userList.get(i);
            //从第二行开始填充数据
            row = sheet.createRow(i+1);
            //该集合记录数量和时间，这两个值来自statisticsModel。如果对象比较复杂，需要额外转换，比如Date类型的日期，int，float类型的数值
            List<String> datas=new ArrayList<>();
            //姓名
            datas.add(tbUser.getNames());
            //用户名
            datas.add(tbUser.getUsername());
            //密码
            datas.add(tbUser.getPassword());
            //账号类型
            Integer type1=tbUser.getType();
            if(type1 == 0){
                datas.add("超级管理员");
            }else if(type1 == 1){
                datas.add("普通管理员");
            }else{
                datas.add("数据未匹配");
            }



            for (int j=0;j<datas.size();j++) {
                String string=datas.get(j);
                HSSFCell cell = row.createCell(j);
                HSSFRichTextString richString = new HSSFRichTextString(string);
                if (string.equals("超级管理员")){
                    HSSFFont font3 = workbook.createFont();
                    //定义Excel数据颜色，这里设置为蓝色
                    font3.setColor(HSSFColor.RED.index);
                    richString.applyFont(font3);
                }
                cell.setCellValue(richString);
            }

        }
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename="+"User.xls");//Excel文件名
        try {
            response.flushBuffer();
            //将workbook中的内容写入输出流中
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    //下载导入模板
    @RequestMapping("/xiazai")
    public void xiazi(HttpServletResponse response) {
        String[] headers = {"姓名","账号","密码","账户类型（超级管理员/普通管理员）"};
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        //设置列宽
        sheet.setDefaultColumnWidth((short) 18);
        //创建第一行的对象，第一行一般用于填充标题内容。从第二行开始一般是数据
        HSSFRow row = sheet.createRow(0);
        for (short i = 0; i < headers.length; i++) {
            //创建单元格，每行多少数据就创建多少个单元格
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            //给单元格设置内容
            cell.setCellValue(text);
        }
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + "UserDemo.xls");//Excel文件名
        try {
            response.flushBuffer();
            //将workbook中的内容写入输出流中
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    //导入excel
    @RequestMapping("/readExcel")
    @ResponseBody
    public BaseBean findImportUser(@RequestParam("fileName") MultipartFile fileName, String suffixName) throws Exception {
        BaseBean bean = new BaseBean();
        try {
            Workbook workbook = null;   //是一种 poi方式
            InputStream is = fileName.getInputStream(); //创建文件的输入流
            if (suffixName.equals("xls")) {
                workbook = new HSSFWorkbook(is);
            } else if (suffixName.equals("xlsx")) {  //xls和xlsx需要不同的workbook对象
                workbook = new XSSFWorkbook(is);
            }
            Sheet sheet = workbook.getSheetAt(0); //
            //最后一行
            int lastRowNum = sheet.getLastRowNum();
            System.out.println(sheet.getLastRowNum());
            for (int rowNum = 1; rowNum <= lastRowNum; rowNum++) {
                Integer ifvin = userService.getAllName(getCellValue(sheet.getRow(rowNum).getCell(1)));
                if (ifvin>0){
                    bean.setMsg("账号"+getCellValue(sheet.getRow(rowNum).getCell(1))+"存在冲突！成功导入前"+(rowNum-1)+"条数据");
                    return bean;
                }
                User user = new User();

                user.setNames(getCellValue(sheet.getRow(rowNum).getCell(0)));
                user.setUsername(getCellValue(sheet.getRow(rowNum).getCell(1)));
                user.setPassword(getCellValue(sheet.getRow(rowNum).getCell(2)));
                String type = getCellValue(sheet.getRow(rowNum).getCell(3));
                int t = 0;
                if (type.equals("普通管理员")){
                    t=1;
                }
                user.setType(t);
                //添加的方法
//                userService.addAccount(account);
            }
            is.close();
            bean.setStatus(200);
            bean.setMsg("导入成功,共导入"+lastRowNum+"条数据");
        } catch (RuntimeException ex) {
            Log.logger.error("操作失败", ex);
            bean.setStatus(400);
            bean.setMsg(ex.getLocalizedMessage());
        }
        return bean;
    }
    public static String getCellValue(Cell cell) {
        String cellValue = "";
        if (cell == null) {
            return cellValue;
        }
        //把数字当成String来读，避免出现1读成1.0的情况
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            cell.setCellType(Cell.CELL_TYPE_STRING);
        }
        //判断数据的类型
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC: //数字
                cellValue = String.valueOf(cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_STRING: //字符串
                cellValue = String.valueOf(cell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN: //Boolean
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA: //公式
                cellValue = String.valueOf(cell.getCellFormula());
                break;
            case Cell.CELL_TYPE_BLANK: //空值
                cellValue = "";
                break;
            case Cell.CELL_TYPE_ERROR: //故障
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知类型";
                break;
        }
        return cellValue;
    }

    //批量删除
    @RequestMapping("/delete")
    @ResponseBody
    public void delete(HttpServletRequest request,HttpServletResponse response){
        String user = request.getParameter("user");
        List<String> delList=new ArrayList<String>();
        String[] strs=user.split(",");
        for(String str : strs){
            delList.add(str);
        }
        userService.delete(delList);
    }
}
